package com.googlecode.garbagecan.dbtest.postgresql;

import java.sql.*;

public class TestPostgreSQLNullColumn {

	//CREATE TABLE "TEST1" (ID VARCHAR(256) NOT NULL, COL1 VARCHAR(256), COL2 NUMERIC(14,4), PRIMARY KEY (ID));
	
	public static void main(String[] args) throws Exception {
		testInsert("" + System.currentTimeMillis(), null, null);
		testInsertSmart("" + System.currentTimeMillis(), null, null);
	}

	private static void testInsert(Object... objs) throws Exception {
		Connection conn = getConnection();
		String sql = "INSERT INTO \"TEST1\"(ID, COL1, COL2) VALUES(?, ?, ?)";
		PreparedStatement ps = conn.prepareStatement(sql);

		int length = objs.length;
		for (int idx = 1; idx <= length; idx++) {
			ps.setObject(idx, objs[idx - 1]);
		}
		ps.executeUpdate();
		conn.commit();
		ps.close();
		conn.close();
	}

	private static void testInsertSmart(Object... objs) throws Exception {
		Connection conn = getConnection();
		String sql = "INSERT INTO \"TEST1\"(ID, COL1, COL2) VALUES(?, ?, ?)";
		PreparedStatement ps = conn.prepareStatement(sql);
		int length = objs.length;
		for (int idx = 1; idx <= length; idx++) {
			if (objs[idx - 1] != null) {
				ps.setObject(idx, objs[idx - 1]);
			} else {
				ps.setNull(idx, Types.NULL);
//				if (ps.getParameterMetaData().getParameterType(idx) == Types.NUMERIC) {
//					ps.setNull(idx, Types.NUMERIC);
//				}  else {
//					ps.setNull(idx, Types.VARCHAR);
//				}
			}
		}
		ps.executeUpdate();
		conn.commit();
		ps.close();
		conn.close();
	}
	
	private static Connection getConnection() throws Exception {
		Class.forName("org.postgresql.Driver");
		String url = "jdbc:postgresql://172.17.18.211/fkong";
		Connection conn = DriverManager.getConnection(url, "fkong", "fkong");
		return conn;
	}
}
